package yicr.panne;



import yicr.Form;
import yicr.GBC;
import yicr.untils.NslUtilString;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.*;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * <h3>Title:</h3>
 * <p>
 *
 * <h3>Description</h3>
 * <p>
 *
 * <h3>Author</h3>
 * <p>
 * Lin Shao
 *
 * @author Lin Shao
 * @version 1.0
 */
public class CnnModelPredictPane extends JPanel {
    private Form form=null;
    private int geohashColumnIndex;

    private static final int DEFAULT_WIDTH=740;
    private static final int DEFAULT_HEIGHT=340;


    private JLabel tipLabel1 =new JLabel("覆盖灰度图路径:");
    private JLabel tipLabel2 = new JLabel(" Cnn模型路径: ");
    private JLabel tipLabel3 =new JLabel("小区场景信息: ");
    private JLabel tipLabel4 =new JLabel(" Cnn模型判别输出: ");


    private JTextField textField1 =null;
    private JTextField textField2 =null;
    private JTextField textField3 =null;
    private JTextField textField4 =null;

    private JLabel unitLabel1 =new JLabel("");
    private JLabel unitLabel2 =new JLabel(" ");
    private JLabel unitLabel3 =new JLabel(" ");
    private JLabel unitLabel4 =new JLabel("");

    private String defaultTextField1 ="";
    private String defaultTextField2 ="";
    private String defaultTextField3 ="";
    private String defaultTextField4 ="";



    private JButton button1 =null;
    private JButton calDataButton=null;

    private JFileChooser fileChooser=null;
    private String importFileAbsPath;

    private List<String> lineList =null;

    public CnnModelPredictPane() throws URISyntaxException {
        initFont();

        //lineList=new ArrayList<>();
        lineList =new ArrayList<>();

        setSize(new Dimension(DEFAULT_WIDTH,DEFAULT_HEIGHT));
//        setResizable(false);

        fileChooser=new JFileChooser();

        FileFilter filter = new FileNameExtensionFilter(
                "Csv files", "csv");
        fileChooser.setFileFilter(filter);


        String basePath=System.getProperty("exe.path");

        // System.out.println(new File("").getAbsolutePath());

        String exePath=new File("").getAbsolutePath()+"\\";



        textField1 =new JTextField();
        textField2 =new JTextField();
        textField3 =new JTextField();
        textField4 =new JTextField();

        int textColumn=15;

        textField1.setColumns(textColumn);
        textField2.setColumns(textColumn);
        textField3.setColumns(textColumn);
        textField4.setColumns(textColumn);


        button1 =new JButton("CNN模型判别");
        calDataButton=new JButton("扫描Mif&Tab导出");


        textField1.setHorizontalAlignment(JTextField.CENTER);
        textField2.setHorizontalAlignment(JTextField.CENTER);
        textField3.setHorizontalAlignment(JTextField.CENTER);
        textField4.setHorizontalAlignment(JTextField.CENTER);

        textField1.setText(defaultTextField1+"");
        textField2.setText(defaultTextField2 +"");
        textField3.setText(defaultTextField3 +"");
        textField4.setText(defaultTextField4 +"");
        String imageAbsPath="d:/antenna_1.png";

        imageAbsPath=Thread.currentThread().getContextClassLoader().getResource("")+"\\tab3_img1.png";
        //imageAbsPath=Thread.currentThread().getContextClassLoader().getResource("")+"\\antenna_1.png";
        imageAbsPath=imageAbsPath.replace("file:","");

        //System.out.println(new File(imageAbsPath).getAbsolutePath());
        JLabel imageLabel=new JLabel(new ImageIcon(imageAbsPath));
        Border etched = BorderFactory.createEtchedBorder();
        imageLabel.setBorder(etched);

        JPanel parameterPanel=new JPanel();

        GridBagLayout gridBagLayoutOfParameterPanel=new GridBagLayout();

        parameterPanel.setLayout(gridBagLayoutOfParameterPanel);

        int top=20;
        int bottom=20;

        parameterPanel.add(tipLabel1,new GBC(0,0,1,1).setAnchor(GridBagConstraints.EAST).setInsets(top,30,15,20));
        parameterPanel.add(tipLabel2,new GBC(0,1,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,30,15,20));
        parameterPanel.add(tipLabel3,new GBC(0,2,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,30,15,20));
        parameterPanel.add(tipLabel4,new GBC(0,3,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,30,bottom,20));

        parameterPanel.add(textField1,new GBC(1,0,1,1).setAnchor(GridBagConstraints.EAST).setInsets(top,0,15,0));
        parameterPanel.add(textField2,new GBC(1,1,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,0,15,0));
        parameterPanel.add(textField3,new GBC(1,2,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,0,15,0));
        parameterPanel.add(textField4,new GBC(1,3,1,1).setAnchor(GridBagConstraints.EAST).setInsets(15,0,bottom,0));

        parameterPanel.add(unitLabel1,new GBC(2,0,1,1).setAnchor(GridBagConstraints.WEST).setInsets(top,5,15,10));
        parameterPanel.add(unitLabel2,new GBC(2,1,1,1).setAnchor(GridBagConstraints.WEST).setInsets(15,5,15,10));
        parameterPanel.add(unitLabel3,new GBC(2,2,1,1).setAnchor(GridBagConstraints.WEST).setInsets(15,5,15,10));
        parameterPanel.add(unitLabel4,new GBC(2,3,1,1).setAnchor(GridBagConstraints.WEST).setInsets(15,5,bottom,10));

        //Border etched = BorderFactory.createEtchedBorder();
        Border titled = BorderFactory.createTitledBorder(etched, "CNN参数设置");

        parameterPanel.setBorder(titled);


        GridBagLayout mainGridBagLayout=new GridBagLayout();

        setLayout(mainGridBagLayout);
        JPanel buttonPanel=new JPanel();
        buttonPanel.add(button1, new GBC(0,0,1,1).setAnchor(GridBagConstraints.CENTER).setInsets(10));

        add(parameterPanel,new GBC(0,0,2,1));
        add(buttonPanel,new GBC(0,1,2,1).setInsets(15));
//        add(calDataButton,new GBC(1,1,1,1).setInsets(15));

        add(imageLabel,new GBC(2,0,1,2).setInsets(5));


        setScreenCenter();
        //pack();

        addEvents();
    }

    private void addEvents() {

        button1.addActionListener(e -> {
            String imagesNpyPath=textField1.getText();
            String modelFilePath=textField2.getText();
            String cellInfoFilePath=textField3.getText();
            String outputFilePath=textField4.getText();

            File imagesDirPathFile=new File(imagesNpyPath);
            File modelFilePathFile=new File(modelFilePath);
            File cellInfoFilePathFile=new File(cellInfoFilePath);
            File outputFilePathFile=new File(outputFilePath);
            if(!imagesDirPathFile.isFile() || !modelFilePathFile.isFile() || !cellInfoFilePathFile.isFile() ){
                JOptionPane.showMessageDialog(CnnModelPredictPane.this, "输入的路径参数不正确，请检查", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            List<String> lineList= NslUtilString.file2StringList(cellInfoFilePathFile,2);
            List<String> idList=new ArrayList<>();

            for (String s : lineList) {
                String[] itemArray=s.split(",");
                idList.add(itemArray[0]);
            }
            System.out.println("size="+idList.size());
            System.out.println("idList="+idList);

            List<String> outputLineList=new ArrayList<>();
            outputLineList.add("id,one-hot-code,angle");


            String oneHotString;


            try {
                oneHotString= cnnPredict(imagesNpyPath,modelFilePath,cellInfoFilePath,outputFilePath);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            String[] oneHotArray=oneHotString.split(";");

            for (int i = 0; i < oneHotArray.length; i++) {
                String id=idList.get(i);
                String oneHotStringItem=oneHotArray[i];
                String angle="65";
                if(oneHotStringItem.equals("0_1_0")){
                    angle="90";
                }else if(oneHotStringItem.equals("0_0_1")){
                    angle="105";
                }
                String line=id+","+oneHotStringItem+","+angle;
                outputLineList.add(line);
            }

            NslUtilString.stringList2File(outputLineList,outputFilePath);
            JOptionPane.showMessageDialog(null, "已生成CNN判决结果");
//            System.out.println(oneHotArray.length);

        });

    }

    private String cnnPredict(String imagesNpyPath,String modelFilePath,String cellInfoFilePath,String outputFilePath) throws InterruptedException, IOException {
        String command="D:\\Python_Projects\\cnn_wireless\\predict.py";
        String exe = "python";
        String[] cmdArr = new String[] {exe,command, imagesNpyPath,modelFilePath};
        Process process = Runtime.getRuntime().exec(cmdArr);
        InputStream is = process.getInputStream();
        DataInputStream dis = new DataInputStream(is);
//        String str = dis.readLine();


        process.waitFor();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(dis));
        String line=null;
        String lastLine=null;
        while ((line=bufferedReader.readLine())!=null){
            System.out.println(line);
            lastLine=line;
        }
        if(lastLine==null){
            JOptionPane.showMessageDialog(null, "检测是否配置Python运行环境");
        }
        //其中one_hot编码： 1_0_0=65,0_1_0=90  0_0_1=105
        System.out.println("*********************");
        System.out.println(lastLine);
        //String[] modelArray=lastLine.split(";");
        return lastLine;

    }


    private void initFont(){
        Font f = new Font("宋体", Font.PLAIN,12);

        String names[]={ "Label", "CheckBox", "PopupMenu","MenuItem", "CheckBoxMenuItem",
                "JRadioButtonMenuItem","ComboBox", "Button", "Tree", "ScrollPane",
                "TabbedPane", "EditorPane", "TitledBorder", "Menu", "TextArea",
                "OptionPane", "MenuBar", "ToolBar", "ToggleButton", "ToolTip",
                "ProgressBar", "TableHeader", "Panel", "List", "ColorChooser",
                "PasswordField","TextField", "Table", "Label", "Viewport",
                "RadioButtonMenuItem","RadioButton", "DesktopPane", "InternalFrame"
        };
        for (String item : names) {
            UIManager.put(item+ ".font",f);
        }
    }

    private void setScreenCenter(){

        int windowWidth = getWidth(); // 获得窗口宽
        int windowHeight = getHeight(); // 获得窗口高
        Toolkit kit = Toolkit.getDefaultToolkit(); // 定义工具包
        Dimension screenSize = kit.getScreenSize(); // 获取屏幕的尺寸
        int screenWidth = screenSize.width; // 获取屏幕的宽
        int screenHeight = screenSize.height; // 获取屏幕的高
        setLocation(screenWidth / 2 - windowWidth / 2, screenHeight / 2 - windowHeight / 2);// 设置窗口居中显示

    }



}
